/* eslint-disable prettier/prettier */

import React, { useEffect, useState } from 'react';
import { DeviceEventEmitter,View, Image, StyleSheet, Text,TextInput, KeyboardAvoidingView,TouchableOpacity ,Modal, ToastAndroid} from 'react-native';
import styles from './DialogStyles';
import CheckBox from '@react-native-community/checkbox';
import { API_BASE,API_PARAMS } from '../../enums/api';
import { DecodeToken } from '../../services/DecodeToken';
import { RootSiblingPortal } from 'react-native-root-siblings';
import AsyncStorage from '@react-native-async-storage/async-storage';
const Loginpage = ({ success,visible,onClose,navigation}) => {
  const [phone, setPhone] = useState('');
  const [passwordcode, setPasswordcode] = useState('');
  const [agree,setAgree] = useState(false);
  useEffect(() => {

  },[visible]);
  //获取当前登录状态下，所持有的密码和账号
  const getInfoAsyncStorage = async () =>{
    AsyncStorage.getItem('token').then((value) => {
      // value 是一个字符串，如果键不存在，则返回 null
      if (value !== null) {
        console.log('AsyncStorage value for ' + 'token' + ': ', value);
        const js = JSON.parse(value);
        const phone = js.phone;
        setPhone(phone);
      } else {
        console.log(value + ' does not exist.');
      }
    }).catch((error) => {
      // 处理错误
      console.error('AsyncStorage error: ', error);
    });
  };
  //注销后send状态刷新给login和home界面
  const quitlogin = async () => {
      try {

        await AsyncStorage.setItem('token','');
       await AsyncStorage.setItem('passwordcode','');
        await AsyncStorage.setItem('phone','');
      DeviceEventEmitter.emit('refreshlogin', false);//给login界面发送信息
        } catch (e){
          //saving error
        }
  };

  const sendlogin = (type) => {
    // 创建一个包含登录信息的JavaScript对象
    const loginInfo = {
        passwordcode: passwordcode, // 确保 passwordcode 已被定义
        phone: phone,               // 确保 phone 已被定义
    };
    let url = '';
    // 构造URL
    if (type === 1)
    {
       url = API_BASE.TEST_URL + API_PARAMS.LOGIN;
    } else if (type === 0){
       url = API_BASE.TEST_URL + API_PARAMS.REGISTER
;    } else if (type === 2){
  quitlogin();
    } else if (type === 3){
      url = API_BASE.TEST_URL + API_PARAMS.LOGOUT;
    }

console.log(url);
   if (type === 1 || type === 0){
    console.log('要注册或登录');
    console.log(loginInfo);
     fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(loginInfo), // 直接使用对象
    })
    .then((response) => {
        // 检查响应是否正常（状态码200-299）
        if (!response.ok) {
            throw new Error('网络响应错误: ' + response.status);
        }
        return response.json();
    })
    .then((data) => {
        console.log('Response:', data);
        // 处理返回的数据
        if (data.msg === 'success') {
            // 登录成功
            alert('登录成功');
            // 发送场景变化的信息
            console.log('setitem' + passwordcode);
            console.log('setitem' + phone);
            AsyncStorage.setItem('passwordcode',passwordcode);
            AsyncStorage.setItem('phone',phone);
              DeviceEventEmitter.emit('login', true);
              DeviceEventEmitter.emit('token', data);
              DecodeToken(data);
              onClose;

        } else {
            // 登录失败
            alert('登录失败: ' + data.msg);
            onClose;
        }
    })
    .catch((error) => {
        console.error('Error:', error);
        alert('请求失败');
    });} else if (type === 3){ 
      getInfoAsyncStorage();
          fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(loginInfo), // 直接使用对象
        })
        .then((response) => {
            // 检查响应是否正常（状态码200-299）
            if (!response.ok) {
                throw new Error('网络响应错误: ' + response.status);
            }
            return response.json();
        })
        .then((data) => {
            console.log('Response:', data);
            // 处理返回的数据
            if (data.msg === 'success') {
                // 登录成功

                // 发送场景变化的信息
                 quitlogin();
                 alert('注销成功');
                  onClose;

            } else {
                // 登录失败

                onClose;
            }
        })
        .catch((error) => {
            console.error('Error:', error);
            alert('请求失败');
        });

    }
};
  if (!visible) {return null;}
  return (
    <Modal
    animationType="slide"
    transparent={true}
    visible={visible}
    onRequestClose={onClose}>
               <View style={styles.dialogContainer}>

{ success ? (
  <KeyboardAvoidingView style={{  justifyContent: 'center', width: '80%'  }}>
    <View style={{ backgroundColor: '#e8f1f8', alignItems: 'center', borderRadius: 20, justifyContent:'center'}}>
      <View style={{ width: '100%', justifyContent: 'center', alignItems: 'center' }}>
        <View style={{ width: '85%', justifyContent: 'center', marginBottom: 20 }}>
        <Text style={{ fontSize: 30, fontWeight: 'bold', margin : 40 ,color:'#2bbceb',textAlign:'center'}}>欢迎加入</Text>
          <TextInput style={{ height: 60, borderBottomColor: 'black', borderBottomWidth: 1 }} placeholder="请输入手机号" placeholderTextColor="gray" onChangeText={(text) => setPhone(text)} />
        </View>
        <View style={{ width: '85%', justifyContent: 'center', marginBottom: 20 }}>
          <TextInput style={{ height: 60, borderBottomColor: 'black', borderBottomWidth: 1 }} placeholder="请输入密码" placeholderTextColor="gray" onChangeText={(text) => setPasswordcode(text)} />
        </View>
      </View>
      <View style={{ width: '100%', flexDirection: 'row', justifyContent: 'center', marginTop: 20}}>
        <TouchableOpacity style={styles.button} onPress={() => {if (agree === true) {sendlogin(1);} else { alert('未同意用户协议');} }}>
          <Text style={{ textAlign: 'center' }}>登录</Text>
        </TouchableOpacity>
        <TouchableOpacity style={styles.button} onPress={() => {if (agree === true) {sendlogin(0);} else { alert('未同意用户协议');} }}>
          <Text style={{ textAlign: 'center' }}>注册</Text>
        </TouchableOpacity>
      </View>
      <View style={{ flexDirection: 'row', alignItems: 'center' ,height:20,margin:20}}>
        <CheckBox
          tintColors={{ true: 'black', false: 'black' }}
          disabled={false}
          value={agree}
          onValueChange={ (value) => setAgree(value)}
        />
        <Text>我已阅读并同意</Text>
        <TouchableOpacity onPress={()=>{ console.log('close'); onClose(); navigation.navigate('contract');}}>
        <Text style={styles.link}>《用户协议》</Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={()=>{ console.log('close'); onClose(); navigation.navigate('privacy');}}>
        <Text style={styles.link}>《隐私政策》</Text>
        </TouchableOpacity>
      </View>
    </View>
  </KeyboardAvoidingView>
) : (
    <View style={{ backgroundColor: '#e8f1f8', alignItems: 'center', borderRadius: 20, justifyContent:'center',width:'100%',height:'20%',bottom:0,position:'absolute'}}>
      <TouchableOpacity style={styles.quit} onPress={()=>{sendlogin(2);}}>
        <Text style={styles.tt}>退出登录</Text>
      </TouchableOpacity>
      <TouchableOpacity style={styles.quit} onPress={() =>{sendlogin(3);}}>
        <Text style={styles.tt}>注销</Text>
      </TouchableOpacity>
    </View>
)}
    </View>
</Modal>
    );
};



export default Loginpage;
